package com;

import org.dom4j.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Xml2Json {

    public static void main(String[] args)  {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Message><ISYS><ServiceCode>30210009</ServiceCode><signature/><GloSno>GCLR2021112920185900168504</GloSno><SceneCode>08</SceneCode><appid>123456</appid><OrgNodeId>CLR</OrgNodeId><nonce>818054506297</nonce><timestamp>1638188340</timestamp></ISYS><Req><czshqlsh>GCLR2021112920185900168502</czshqlsh><shifouyj>2</shifouyj><faxifdbl>50</faxifdbl><faxililv>0.0975000</faxililv><hzfzhenjham>91520000214413986L</hzfzhenjham><jizhunll>3.85</jizhunll><shfzhjdb/><contentArray><signContract/><contentID>202111_67_750_E9D822C2-1A4F-7B90-3D03-D21B5102781B-8</contentID><fileTpye>01</fileTpye></contentArray><contentArray><signContract>QT20211129000004211</signContract><contentID>202111_532_494_074BAC82-3331-4488-765B-8F750FB50D20-8</contentID><fileTpye>05</fileTpye></contentArray><contentArray><signContract>JK20211129000026687</signContract><contentID>202111_999_320_3706129A-F4C6-DB17-2ED0-460BCFB412FF-8</contentID><fileTpye>02</fileTpye></contentArray><contentArray><signContract>QT20211129000004213</signContract><contentID>202111_858_135_10F59C93-9746-E828-CA23-C497ED416254-8</contentID><fileTpye>03</fileTpye></contentArray><huanrirr>2021-11-30</huanrirr><qixiriqi>2021/11/29</qixiriqi><lstdanbArray><chuzrzjh>9152040066697547X1</chuzrzjh><pingyxqi>01</pingyxqi><chipiaor/><danbaoje/><shifdysw>1</shifdysw><chupiaor/><zhiwujie>222.0000</zhiwujie><quanzhao/><pingfanf>01</pingfanf><chduihmc/><qianfarq>2021-11-23</qianfarq><pjuhaoma/><czrdkkha>210220400000041</czrdkkha><mianpije>222.0000</mianpije><zhiyabiz>01</zhiyabiz><czrzjlxi>Ent04</czrzjlxi><zhiwulxi>002001</zhiwulxi><chuzrmic>贵州黄果树金叶科技有限公司</chuzrmic><daoqiriq>2021-11-30</daoqiriq><zhanglin>0.0</zhanglin><ghuoshmc/><yinszkje>222.0000</yinszkje></lstdanbArray><shifoufp>2</shifoufp><bizhonga>01</bizhonga><huankplv>3</huankplv><fankjine>199.800000</fankjine><lilvfana>1</lilvfana><danblexx>010</danblexx><zhifufas>010</zhifufas><chanpbha>1096060</chanpbha><fankzhha>210220400000041</fankzhha><qixianyu/><shifousn>N</shifousn><zijinytu>1</zijinytu><qixianti>0</qixianti><daqiriqi>2021/11/30</daqiriqi><contentID/><yongtuaa>01</yongtuaa><shiflsdk>N</shiflsdk><jzlilvll>070</jzlilvll><zhenjham>9152040066697547X1</zhenjham><daiktoxi>B06</daiktoxi><shfkjidk>2</shfkjidk><lilvtzfs>2</lilvtzfs><lilvfdfs>1</lilvfdfs><shifyddk>010</shifyddk><danbzjie/><shifsqfl>N</shifsqfl><shifkcdk>2</shifkcdk><zhenjlex>Ent04</zhenjlex><hzfzhenjlex>Ent04</hzfzhenjlex><huankfas>RPT-03</huankfas><zijinlay>0010</zijinlay></Req></Message>";
        String json = xmlToJson(xml);
        System.out.println(json);


    }
    /**
     * 将xml文件转换成json字符串
     * @param filePath xml文件路径
     * @return
     * @throws Exception
     */
    public static String xmlToJson(String xml) {
        Document document = null;
        try {
            document = DocumentHelper.parseText(xml);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        return tojson(root.elements());
    }


    /**
     * 将根元素下的元素转换成json字符串
     * @param element
     * @return
     */
    public static String tojson(List<Element> element){
        /**
         * 1.存储每以层的结果，key为标签的名字，value为每层标签解析后的结果
         * 2.相同的标签会用逗号拼接，组成json数组
         */
        Map<String, String> resultMap = new HashMap<String, String>();
        Map<String, Integer> countMap = new HashMap<String, Integer>();
        //解析一层中的所有标签
        for(Element ele:element){

            String resultJson = "{";

            String labelName = ele.getName();
            //如果标签中有文本，则对应到json中为：labelName + "Text:"：value
            String text = ele.getTextTrim();
            if (text.length()>0) {
                resultJson += labelName + "Text:" + text + "," ;
            }
            resultJson += attributesToJson(ele);
            String tojson = tojson(ele.elements());
            if (tojson.length()>0&&resultJson.length()>1) {
                resultJson += ",";
            }
            resultJson += tojson + "}";
            String result = resultMap.get(ele.getName());
            //将相同的标签解析后的json字符串用逗号拼接起来
            if(result!=null){
                resultMap.put(labelName, result+","+resultJson);
                countMap.put(labelName, countMap.get(labelName) + 1);
            }else {
                resultMap.put(labelName, resultJson);
                countMap.put(labelName, 1);
            }
        }
        //将一层所有的标签json字符串拼接起来
        String json = "";
        for(Map.Entry<String, String> entry:resultMap.entrySet()){
            if (countMap.get(entry.getKey())>1) {
                json += "\"" + entry.getKey() + "\"" + ":[" + entry.getValue() + "]";
            }else {
                json += "\"" + entry.getKey() + "\"" + ":" + entry.getValue() ;
            }
            json += ",";
        }
        if (json.length()>0) {
            return json.substring(0, json.length()-1);
        }
        return json;
    }

    /**
     * 将标签的属性值转换成json字符串
     * @param element
     * @return
     */
    public static String attributesToJson(Element element){
        String attrJson = "";
        List<Attribute> attributes = element.attributes();
        for(Attribute attr:attributes){
            attrJson += "," + "\"" + attr.getName() + "\"" + ":" + "\"" + attr.getValue() + "\"";
        }
        if (attrJson.length()>0) {
            return attrJson.substring(1);
        }
        return attrJson;
    }
}
